package com.jbookstore.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.jbookstore.dto.BookDto;
import com.jbookstore.dto.OrderDetailDto;
import com.jbookstore.dto.OrderDto;
import com.jbookstore.service.BookService;
import com.jbookstore.service.OrderService;

@Controller
public class OrderController extends CommonController {
	
	@Autowired 
	private BookService bookService;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "order.do", method = RequestMethod.GET)
	public ModelAndView order(
			@RequestParam(value="selectedBookIds", required=true) String bookIds) {
		
		ModelAndView mav = new ModelAndView();
		try {
			
			List<BookDto> books = bookService.getBookListByIds(bookIds);
			mav.addObject("books", books);
			mav.setViewName("/order/order");
		} 
		
		catch (Exception e) {
			mav = this.errorHandler(e);
		}
		
		return mav;
	}
	
	@RequestMapping(value = "payment.do", method = RequestMethod.POST)
	public void payment(
			@RequestParam(value="bookIds", required=true) String bookIds,
			@RequestParam(value="counts", required=true) String counts,
			@RequestParam(value="userId", required=true) String userId,
			@RequestParam(value="name", required=true) String name,
			@RequestParam(value="address", required=true) String address,
			@RequestParam(value="phoneNum", required=true) String phoneNum) {
		
		logger.info(bookIds);
		logger.info(counts);
		
		OrderDto order = new OrderDto();
		
		try {
			
			String[] bookIdArr = bookIds.split(",");
			String[] countArr = counts.split(",");
			
			logger.info(bookIdArr);
			
			// 주문 아이디 부여
			order.setOrder_id(orderService.getOrderId());
			
			// 주문 객체
			order.setUser_id(userId);
			order.setCode_id("O001");
			order.setCodegroup_id("O");
			order.setName(name);
			order.setAddress(address);
			order.setPhone_num(phoneNum);
			
			for (int i = 0, len = bookIdArr.length; i < len; i++) {
				
				OrderDetailDto orderDetail = new OrderDetailDto();
				
				orderDetail.setOrder_id(order.getOrder_id());
				orderDetail.setBook_id(bookIdArr[i]);
				orderDetail.setQty(Integer.parseInt(countArr[i]));
				
//				order.getOrders().add(orderDetail);
				
				logger.info(orderDetail);
			}
			
		} catch (Exception e) {
			logger.info(e);
		}
		
		logger.info(order);
//		return "redirect:main.do";
	}
}
